import userApi from '@/api/user';
import router, { resetRouter } from '@/router/index';
import {allAsyncRoutes, anyRoutes, Routes} from '@/router/routes';

// 从所有的异步路由中过滤自己的异步路由
function filterAsyncRoutes(allAsyncRoutes, routeName){
  return allAsyncRoutes.filter(item => {
    if(routeName.indexOf(item.name) !== -1){
      if(item.children && item.children.length){
        item.children = filterAsyncRoutes(item.children, routeName);
      }
      return true
    }
  })
}

function addRoute(routes){
  routes.forEach(item => {
    router.addRoutes([item])
  });
}

const state = {
  token: localStorage.getItem('token_key') || '',
  userInfo: {
    name: '',
    avatar: ''
  }
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO(state, userInfo){
    state.userInfo = userInfo;
  },
  RESET_TOKEN(state){
    state.token = '';
  },
  RESET_USERINFO(state){
    state.userInfo = {};
  }
}

const actions = {
  // 点击登录
  async login({commit}, userInfo){
    try {
      const result = await userApi.userLogin(userInfo);
      // console.log(result);
      if(result.code === 20000){
        commit('SET_TOKEN', result.data.token);
        localStorage.setItem('token_key', result.data.token);
        return 'ok'
      }else{
        return Promise.reject(new Error('faild'));
      }
    } catch (error) {
      return Promise.reject(new Error('faild'));
    }
  },

  // 获取用户信息
  async getInfo({commit}){
    try {
      const result = await userApi.getUserInfo();
      // console.log(result);
      // 1.根据用户登录, 获得的routes, 从所有异步路由中过滤自己的异步路由
      let userAsyncRoutes = filterAsyncRoutes(allAsyncRoutes, result.data.routes);
      // console.log(userAsyncRoutes);

      
      // 2.把自己的异步路由动态添加到路由器中, 吧任意路由添加注册到最后一位
      addRoute(userAsyncRoutes.concat(anyRoutes));
      // router.addRoutes([...userAsyncRoutes, ...anyRoutes])
      // console.log(userAsyncRoutes.concat(anyRoutes));
      
      // // 遍历动态注册后的路由
      // router.option.routes = Routes.concat(userAsyncRoutes, anyRoutes);
      router.options.routes = [...router.options.routes, ...userAsyncRoutes, ...anyRoutes]

      if(result.code === 20000){
        commit('SET_USERINFO', result.data);
        return 'ok'
      }else{
        return Promise.reject(new Error('faild'));
      }
    } catch (error) {
      return Promise.reject(new Error('faild'));
    }
  },

  // 清空token
  resetToken({commit}){
    commit('RESET_TOKEN');
    localStorage.removeItem('token_key');
  },

  // 退出登录
  async logout({commit,dispatch}){
    // console.log(commit);
    try {
      await userApi.userLogout();
      dispatch('resetToken');
      commit('RESET_USERINFO');
      // 重置路由
      resetRouter()

      return 'ok';
    } catch (error) {
      return Promise.reject(new Error('faild'));
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

